import React, { Component } from 'react';
import Uploader from './uploader';
export default class HtmlEditor extends Component {
  state = {
    process:"Please select a directory to upload.",disabled:false};
  uploadFile = e => {
    console.log(e);
    // var button = e.target;
    // button.disabled = true;
    this.setState({disabled:true});
    this.setState({process:'0%'})
    var files = e.target.files;
    var totalFiles = files.length;
    var filesSent = 0;
    var __this=this;
    if (totalFiles) {
      var uploader = new Uploader('ws://localhost:8080', function() {
        Array.prototype.slice.call(files, 0).forEach(function(file) {
          if (file.name === '.') {
            --totalFiles;
            return;
          }
          uploader.sendFile(file, function(error) {
            if (error) {
              console.log(error);
              return;
            }
            ++filesSent;
            let progress_innerHTML = ~~((filesSent / totalFiles) * 100) + '%';
            __this.setState({process:progress_innerHTML});
            console.log('Sent: ' + file.name);
          });
        });
      });
    }
    uploader.ondone = function() {
      uploader.close();
      let progress_innerHTML = '100% done, ' + totalFiles + ' files sent.';
      __this.setState({process:progress_innerHTML});
      __this.setState({disabled:false});
    };
  };
  render() {
    // console.log(this.state);
    let content = `<style>${this.state.css}</style>${this.state.html}`;
    // content = content.replace(
    //   '<head>',
    //   `<head><base href="${this.state.filename}" >`
    // );
    return (
      <div>
        <p>
          This example will upload an entire directory tree to the node.js
          server via a fast and persistent WebSocket connection.
        </p>
        <p>Note that the example is Chrome only for now.</p>
        <input onChange={this.uploadFile} type="file" webkitdirectory="true" disabled={this.state.disabled} />
        <br />
        <br />
        Upload status:
        <div id="progress">{this.state.process}</div>
      </div>
    );
  }
}
